package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.Vessel;
import Models.VesselCleaningProcedure;

public class VesselPresenter extends AbstractPresenter<Vessel> {
	final String SINGLEITEM = "fv";
	final String MULTIITEM = "fvs";
	
	public ArrayList<Vessel> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public Vessel tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public Vessel createItemFromJSONObject(JSONObject jsonObject){
		Vessel item = new Vessel();
		try{
			item.setVesselCapacity(jsonObject.getDouble("FVCap"));
			item.setVesselDesignation(jsonObject.getString("FVDesg"));
			item.setVesselID(jsonObject.getInt("fvid"));
			item.setVesselMfg(jsonObject.getString("FVMfg"));
			item.setVesselName(jsonObject.getString("FVName"));
			item.setVesselPrimary(jsonObject.getBoolean("fvprm"));
			item.setVesselRating(jsonObject.getDouble("FVRate"));
			
			//Set VCP Collection
			ArrayList<VesselCleaningProcedure> vcps = new ArrayList<VesselCleaningProcedure>();
			if(!jsonObject.isNull("vcpCollection")){
				Object itm = jsonObject.get("vcpCollection");
				VesselCleaningProcedurePresenter presenter = new VesselCleaningProcedurePresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						vcps.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					vcps.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setProcedures(vcps);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Vessel item){
		try{
			JSONObject json = new JSONObject();
			json.put("FVCap", item.getVesselCapacity());
			json.put("FVDesg", item.getVesselDesignation());
			json.put("fvid", item.getVesselID());
			json.put("FVMfg", item.getVesselMfg());
			json.put("FVName", item.getVesselName());
			json.put("fvprm", item.getVesselPrimary());
			json.put("FVRate", item.getVesselRating());
			
			//Create VCP Collection
			if(item.getProcedures()!=null){
				VesselCleaningProcedurePresenter presenter = new VesselCleaningProcedurePresenter();
				if(item.getProcedures().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getProcedures().size(); i++){
						jsonArray.put(presenter.createJSON(item.getProcedures().get(i)));
					}
					json.put("vcpCollection", jsonArray);
				}
			}

			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Vessel getEmptyEntity(){
		Vessel entity = new Vessel();
		return entity;
	}
}
